package com.jcli._java_swing_入门教程pdf.ch17._09_Calculator;

import com.jcli.util._获取并保存窗体大小.WindowSizeManager;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 1.实现界面
 * 2.实现计算功能
 * 3.添加操作过程
 *
 * @author li
 * @version 1.0
 * @belongsProject novel_20230923
 * @belongsPackage com.jcli._java_swing_入门教程pdf.ch17._09_Calculator
 * @className CalculatorDemo
 * @description TODO  计算器界面
 * @createTime 2024-02-01  09:17
 */
public class CalculatorDemo01  {
    /**
     * 内容面板
     */
    private JPanel contentPane;
    /**
     * 文本框
     */
    private JTextField textField;
    // 用于存储输入的数字和操作符
    private StringBuilder inputBuffer = new StringBuilder();
    private JTextField processTextField;  // 用于显示操作过程


    public static void main(String[] args) {
        CalculatorDemo01 frame = new CalculatorDemo01();
        // frame.setVisible(true);
    }

    /**
     * 构造方法
     */
    public CalculatorDemo01() {
        JFrame frame = new JFrame();
        //2.设置窗体标题
        frame.setTitle("计算器");
        //    设置窗体退出时操作
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //    设置窗体位置大小
        frame.setBounds(100, 100, 250, 200);

        // Apply the saved window size
        WindowSizeManager.applyWindowSize(frame);

        //    创建内容面板
        contentPane = new JPanel();
        //    设置面板边框
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        //    设置内容面板为边界布局
        contentPane.setLayout(new BorderLayout(0, 0));
        //    应用内容面板
        frame.setContentPane(contentPane);
        //    新建面板用于保存文本框
        JPanel panel1 = new JPanel();
        //    将文本框放在边界布局北部
        contentPane.add(panel1, BorderLayout.NORTH);
        //    新建文本框
        textField = new JTextField();
        //    文本框中的文本使用右对齐
        textField.setHorizontalAlignment(SwingConstants.RIGHT);
        //    将文本框加入面板
        panel1.add(textField);
        //    设置文本框列数为18
        textField.setColumns(18);

        // 添加一个文本框用于显示操作过程
        processTextField = new JTextField();
        processTextField.setHorizontalAlignment(SwingConstants.RIGHT);
        panel1.add(processTextField);
        processTextField.setColumns(18);

        //    3.使用网格布局器添加多个按钮作为计算器的键盘区
        //    新建面板用于保存按钮
        JPanel jPanel2 = new JPanel();
        //面板放置布局中央
        contentPane.add(jPanel2, BorderLayout.CENTER);
        //    面板使用网格4*4布局
        jPanel2.setLayout(new GridLayout(4, 4, 5, 5));
        // jPanel2.setLayout(new CardLayout(4,4));
        //    新建按钮并且应用按钮
        String num = "7,8,9,+,4,5,6,-,3,2,1,*,0,.,=,/,C";
        for (int i = 0; i < num.length(); i++) {
            char c = num.charAt(i);
            if (c != ',') {
                // jPanel2.add(new JButton(Character.toString(c)));
                JButton button = new JButton(Character.toString(c));
                // 为每个按钮添加点击事件
                button.addActionListener(new CalculatorButtonListener());
                jPanel2.add(button);
            }
        }
        frame.setVisible(true);

        // Save the window size when it's closed
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                WindowSizeManager.saveWindowSize(frame);
            }
        });

    }

    // 内部类，用于处理按钮点击事件
    class CalculatorButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String buttonText = source.getText();

            // 如果点击的是 "="，进行计算
            if (buttonText.equals("=")) {
                calculateResult();
            } else if (buttonText.equals("C")) {
                clearInput();
            } else {
                // 其他情况，追加到输入缓冲区
                inputBuffer.append(buttonText);
                textField.setText(inputBuffer.toString());
                processTextField.setText(inputBuffer.toString());
            }
        }
    } // 计算结果

    private void calculateResult() {
        try {
            // 利用JavaScript引擎进行计算
            String expression = inputBuffer.toString();
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            Object result = engine.eval(expression);

            // 显示结果
            textField.setText(result.toString());

            processTextField.setText(expression);

            // 清空输入缓冲区
            inputBuffer.setLength(0);
        } catch (ScriptException ex) {
            // 计算异常，清空输入缓冲区并提示错误
            inputBuffer.setLength(0);
            textField.setText("错误");
            processTextField.setText("");
        }
    }

    private void clearInput() {
        inputBuffer.setLength(0);
        textField.setText("");
        processTextField.setText("");
    }
}
